//
//  PageMapView.m
//  KidReading
//
//  Created by telen on 15/2/6.
//  Copyright (c) 2015年 刘赞黄Telen. All rights reserved.
//

#import "PageMapView.h"
#import "ConstDefine.h"

@implementation MicroPageView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = __BaseBackColor2;
        self.clipsToBounds = YES;
        //
        CGFloat pod = 2;
        imgv = [[UIImageView alloc] initWithFrame:CGRectMake(pod, pod, frame.size.width-pod-pod, frame.size.height)];
        [self addSubview:imgv];
        //
        CGFloat lh = ceil(frame.size.height*0.16);
        label = [[UILabel alloc] initWithFrame:CGRectMake(0, frame.size.height-lh, frame.size.width, lh)];
        [self addSubview:label];
        label.font = [UIFont boldSystemFontOfSize:label.size.height*0.8];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = __BaseBackColor2;
        label.shadowColor = [UIColor clearColor];
        label.alpha = 0.96;
    }
    return self;
}

- (void)setPageIndex:(NSInteger)index
{
    label.text = [NSString stringWithFormat:@"%d",(int)index];
}

- (void)setPageStr:(NSString*)str
{
    label.text = str;
}

- (void)setShowImage:(UIImage *)image
{
    if (!image)return;
    CGFloat rt = imgv.frame.size.width/image.size.width;
    CGRect frame = imgv.frame;
    frame.size.height = image.size.height*rt;
    imgv.frame = frame;
    imgv.image = image;
}

- (void)setHighlight:(BOOL)yn
{
    if (yn) {
        self.backgroundColor = __BaseBackColor1;
        label.backgroundColor = __BaseBackColor1;
        label.textColor = __BaseBackColor5;
    }else{
        self.backgroundColor = __BaseBackColor2;
        label.backgroundColor = __BaseBackColor2;
        label.textColor = __BaseBackColor4;
    }
}

@end

@implementation PageMapView

- (void)dealloc
{
    self.pagesArr = nil;
    self.pageDisArr = nil;
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}

- (void)flashPageMap
{
    if (!carousel) {
        ratio = 150.0/_mapHeigth;
        self.translatesAutoresizingMaskIntoConstraints = NO;
        [self lyt_alignLeftToParent];
        [self lyt_alignRightToParent];
        [self lyt_alignBottomToParentWithMargin:0];
        [self lyt_setHeight:_mapHeigth];
        //
        self.backgroundColor = __BaseBackColor3;
        //
        UITapGestureRecognizer* unDoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapUndo)];
        unDoTap.delegate = [TLGestureRecognizerDelegate shareSingleTapView_Undo];
        [self addGestureRecognizer:unDoTap];
        //
        carousel = [[JRiCarousel alloc] init];
        [self addSubview:carousel];
        carousel.translatesAutoresizingMaskIntoConstraints = NO;
        [carousel lyt_alignToParent];
        carousel.type = JRiCarouselTypeRotary;
        carousel.delegate = self;
        carousel.dataSource = self;
        [carousel setCurrentItemIndex:_currentIndex];
    }else{
        [carousel reloadData];
        [carousel setCurrentItemIndex:_currentIndex];
    }
}

- (void)flashCurrentIndex
{
    [currentMview setHighlight:NO];
    currentMview = (MicroPageView*)[carousel itemViewAtIndex:_currentIndex];
    [currentMview setHighlight:YES];
    [carousel setCurrentItemIndex:_currentIndex];
}


- (NSInteger)numberOfItemsInCarousel:(JRiCarousel *)carousel
{
    return _pagesArr.count;
}

- (UIView *)carousel:(JRiCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
    MicroPageView* mview = (MicroPageView*)view;
    if (!view) {
        mview = [[MicroPageView alloc] initWithFrame:CGRectMake(0, 0, ceil(145/ratio), ceil(125/ratio))];
        view = mview;
    }
    //[mview setPageIndex:(index+1)];
    [mview setPageStr:[self.pageDisArr objectAtIndex:index]];
    NSDictionary* dict = [_pagesArr objectAtIndex:index];
    nullToNil(dict);
    NSString* thumb = [dict objectForKey:@"thumb"];
    nullToNil(thumb);
    NSNumber* numType = [dict objectForKey:@"type"];
    nullToNil(numType);
    NSInteger type = -1;
    if(numType)type = numType.integerValue;
    if ((thumb && thumb.length>0) || type == BookPageType_pAccessibility) {
        NSString* path = [DataProcessing bookPathForBookID:_bookid subDir:thumb];
        UIImage* image = nil;
        if (BookPageType_pQuiz == type) {
            image = [UIImage imageNamed:@"quiz_thumb.jpg"];
        }
        if (BookPageType_pAccessibility == type) {
            image = [UIImage imageNamed:@"func_thumb.jpg"];
        }
        if(path &&!image)image = [UIImage imageWithContentsOfFile:path];
        [mview setShowImage:image];
    }
    if (_currentIndex == index) {
        [mview setHighlight:YES];
        currentMview = mview;
    }else{
        [mview setHighlight:NO];
    }
    return view;
}

- (CGFloat)carousel:(JRiCarousel *)carousel valueForOption:(JRiCarouselOption)option withDefault:(CGFloat)value
{
    switch (option)
    {
        case JRiCarouselOptionArc:
            return 0.001;
        case JRiCarouselOptionFadeMin:
            return -0.01;
        case JRiCarouselOptionFadeMax:
            return 0.01;
        case JRiCarouselOptionFadeRange:
            return 5.0;
        case JRiCarouselOptionSpacing:
            return 1.1;
        case JRiCarouselOptionFadeMinAlpha:
            return 0.6;
        default:
            return value;
    }
}

- (void)carousel:(JRiCarousel *)carousel_ didSelectItemAtIndex:(NSInteger)index
{
    [currentMview setHighlight:NO];
    currentMview = (MicroPageView*)[carousel itemViewAtIndex:index];
    [currentMview setHighlight:YES];
    if (_delegate && [_delegate respondsToSelector:@selector(pageMapViewDidSelectPageIndex:)]) {
        [_delegate pageMapViewDidSelectPageIndex:index];
        //
        [NSObject msgToClassName:@"TLMobStat" menthed:@"logEvent:eventLabel:" refs:@[RE_main,@"缩微图点击"] needReturnValue:NO];
    }
}

#define BeginDe_Offset "BeginDeceleratingOffset"
- (void)carouselWillBeginDragging:(JRiCarousel *)carousel_;
{
    objc_setAssociatedObject(carousel_, BeginDe_Offset, @(carousel_.scrollOffset), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)carouselDidEndDragging:(JRiCarousel *)carousel_ willDecelerate:(BOOL)decelerate
{
    if (!decelerate) {
        objc_setAssociatedObject(carousel_, BeginDe_Offset, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}

- (void)carouselDidEndDecelerating:(JRiCarousel *)carousel_;
{
    NSNumber* num = objc_getAssociatedObject(carousel_, BeginDe_Offset);
    if (num) {
        CGFloat offset = num.floatValue;
        if ((offset > 0 && offset > carousel_.scrollOffset && carousel_.startVelocity > 0)
            || (offset > 0 && offset < carousel_.scrollOffset && carousel_.startVelocity < 0)
            ){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [carousel_ scrollToItemAtIndex:0 animated:YES];
            });
        }
    }
    objc_setAssociatedObject(carousel_, BeginDe_Offset, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    //
    //NSLog(@">> %@ %@ %@",@(carousel_.scrollOffset),@(carousel_.offsetMultiplier),@(carousel_.startVelocity));
}


- (void)didTapUndo{}

- (void)show
{
    for (NSLayoutConstraint* constraint in self.superview.constraints) {
        if (constraint.firstAttribute == NSLayoutAttributeBottom) {
            if (constraint.firstItem == self
                && fabsf(constraint.constant) > 0.1 ) {
                CGRect frame = self.frame;
                frame.origin.y -= _mapHeigth;
                [UIView animateWithDuration:0.3 animations:^{
                    constraint.constant = 0;
                    self.frame = frame;
                    [self layoutIfNeeded];
                }completion:^(BOOL finished) {
                    constraint.constant = 0;
                    [self layoutIfNeeded];
                }];
            }
        }
    }
}

- (void)unShow
{
    for (NSLayoutConstraint* constraint in self.superview.constraints) {
        if (constraint.firstAttribute == NSLayoutAttributeBottom) {
            if (constraint.firstItem == self
                && fabsf(constraint.constant) < 0.1 ) {
                CGRect frame = self.frame;
                frame.origin.y += _mapHeigth;
                [UIView animateWithDuration:0.3 animations:^{
                    constraint.constant = _mapHeigth;
                    self.frame = frame;
                    [self layoutIfNeeded];
                }completion:^(BOOL finished) {
                    constraint.constant = _mapHeigth;
                    [self layoutIfNeeded];
                }];
            }
        }
    }
}

@end
